const express = require('express');
const path = require('path');
const timeStamp = require('time-stamp');
const fs = require('fs');
const router = express.Router();

//get-register
//读取静态资源
router.use('/static',express.static(path.resolve(__dirname,'./static')));
//
router.get('/register',(req,res)=>{
    res.sendFile(path.resolve(__dirname,'../views/register.html'));
});

// 接收前端的json对象
router.use(express.urlencoded({extended:false}))

//post-register
router.post('/register',(req,res,next)=>{
    //获取当前时间
    let time = timeStamp('YYYY年MM月DD日 HH:mm:ss');
    // 解构赋值
    let {username,password,password2} = req.body;
    //读取persons文件
    let file = fs.readFileSync('./data/persons.json','utf-8');
    //
    file = JSON.parse(file)
    //
    let o = file.findIndex(item => item.username == username);
    let q = password == password2;
    if( o == -1 && q ){
        file.push({username,password,time});
        fs.writeFileSync('./data/persons.json',JSON.stringify(file));
        res.send('注册成功')
        return;
    }
    //判断两次密码是否相同
    else if( !q ){
        next('两次密码不一致');
    }else if( o != -1 ){
        next('账号已被注册');
    };
});



// router.use((err,req,res,next)=>{
//     console.log(err);
//     res.status(555);
//     res.send(`<h1>${err}</h1>`);
// });

// router.use((req,res)=>{
//     res.status(404);//设置状态码
//     res.send({
//         status:404,
//         code:'not found',
//     });
// });


module.exports = router;